<template>
  <div class="page-container">
    <div class="content-box">
      <h2>资源管理</h2>
      
      <!-- 统计卡片 -->
      <el-row :gutter="20" class="mb-20">
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon" style="background: #409EFF;">
              <i class="el-icon-folder"></i>
            </div>
            <div class="stat-content">
              <div class="stat-title">总资源数</div>
              <div class="stat-value">{{ statistics.totalResources || 0 }}</div>
            </div>
          </div>
        </el-col>
        
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon" style="background: #E6A23C;">
              <i class="el-icon-warning-outline"></i>
            </div>
            <div class="stat-content">
              <div class="stat-title">待审核</div>
              <div class="stat-value">{{ statistics.pendingAuditResources || 0 }}</div>
            </div>
          </div>
        </el-col>
        
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon" style="background: #67C23A;">
              <i class="el-icon-download"></i>
            </div>
            <div class="stat-content">
              <div class="stat-title">总下载数</div>
              <div class="stat-value">{{ statistics.totalDownloads || 0 }}</div>
            </div>
          </div>
        </el-col>
        
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon" style="background: #F56C6C;">
              <i class="el-icon-warning"></i>
            </div>
            <div class="stat-content">
              <div class="stat-title">违规资源</div>
              <div class="stat-value">{{ statistics.violationResources || 0 }}</div>
            </div>
          </div>
        </el-col>
      </el-row>
      
      <!-- 搜索筛选 -->
      <el-form :model="queryForm" :inline="true" class="search-form">
        <el-form-item label="关键词">
          <el-input v-model="queryForm.keyword" placeholder="搜索标题和描述" clearable style="width: 200px"></el-input>
        </el-form-item>
        
        <el-form-item label="上传者">
          <el-input v-model="queryForm.uploaderName" placeholder="请输入上传者姓名" clearable style="width: 150px"></el-input>
        </el-form-item>
        
        <el-form-item label="资源类型">
          <el-select v-model="queryForm.resourceType" placeholder="请选择类型" clearable style="width: 120px">
            <el-option label="文档" value="document"></el-option>
            <el-option label="视频" value="video"></el-option>
            <el-option label="音频" value="audio"></el-option>
            <el-option label="图片" value="image"></el-option>
            <el-option label="课程" value="course"></el-option>
            <el-option label="其他" value="other"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="来源">
          <el-select v-model="queryForm.source" placeholder="请选择来源" clearable style="width: 120px">
            <el-option label="社区" value="community"></el-option>
            <el-option label="教师" value="teacher"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="学科">
          <el-select v-model="queryForm.subject" placeholder="请选择学科" clearable style="width: 120px">
            <el-option label="数学" value="math"></el-option>
            <el-option label="物理" value="physics"></el-option>
            <el-option label="化学" value="chemistry"></el-option>
            <el-option label="生物" value="biology"></el-option>
            <el-option label="其他" value="other"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="状态">
          <el-select v-model="queryForm.resourceStatus" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="草稿" :value="0"></el-option>
            <el-option label="待审核" :value="1"></el-option>
            <el-option label="已发布" :value="2"></el-option>
            <el-option label="已下架" :value="3"></el-option>
            <el-option label="已删除" :value="4"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch" icon="el-icon-search">搜索</el-button>
          <el-button @click="handleReset" icon="el-icon-refresh">重置</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 批量操作 -->
      <div class="toolbar">
        <div class="toolbar-left">
          <el-button 
            type="primary" 
            @click="batchAudit(1)" 
            :disabled="selectedResources.length === 0"
            icon="el-icon-check">
            批量通过
          </el-button>
          <el-button 
            type="warning" 
            @click="batchAudit(2)" 
            :disabled="selectedResources.length === 0"
            icon="el-icon-close">
            批量拒绝
          </el-button>
          <el-button 
            type="success" 
            @click="batchPublish" 
            :disabled="selectedResources.length === 0"
            icon="el-icon-upload">
            批量发布
          </el-button>
          <el-button 
            type="danger" 
            @click="batchTakeDown" 
            :disabled="selectedResources.length === 0"
            icon="el-icon-download">
            批量下架
          </el-button>
        </div>
        
        <div class="toolbar-right">
          <el-button type="text" @click="handleRefresh" icon="el-icon-refresh">刷新</el-button>
        </div>
      </div>
      
      <!-- 资源列表 -->
      <el-table 
        :data="resourceList" 
        v-loading="loading"
        @selection-change="handleSelectionChange"
        stripe
        border>
        <el-table-column type="selection" width="55"></el-table-column>
        
        <el-table-column prop="title" label="标题" width="200">
          <template slot-scope="scope">
            <el-link type="primary" @click="viewResourceDetail(scope.row)">{{ scope.row.title }}</el-link>
          </template>
        </el-table-column>
        
        <el-table-column prop="uploaderName" label="上传者" width="100">
          <template slot-scope="scope">
            <div>{{ scope.row.uploaderName }}</div>
            <el-tag size="mini" :type="getUploaderTypeColor(scope.row.uploaderType)">
              {{ getUploaderTypeText(scope.row.uploaderType) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="资源信息" width="150">
          <template slot-scope="scope">
            <div>类型: {{ getResourceTypeText(scope.row.resourceType) }}</div>
            <div>来源: {{ getSourceText(scope.row.source) }}</div>
            <div>学科: {{ getSubjectText(scope.row.subject) }}</div>
          </template>
        </el-table-column>
        
        <el-table-column label="文件信息" width="120">
          <template slot-scope="scope">
            <div>{{ scope.row.fileName }}</div>
            <div style="color: #909399; font-size: 12px;">{{ getFileSizeText(scope.row.fileSize) }}</div>
          </template>
        </el-table-column>
        
        <el-table-column label="状态" width="100">
          <template slot-scope="scope">
            <div>
              <el-tag :type="getResourceStatusType(scope.row.resourceStatus)">
                {{ getResourceStatusText(scope.row.resourceStatus) }}
              </el-tag>
            </div>
            <div style="margin-top: 4px;">
              <el-tag size="mini" :type="getAuditStatusType(scope.row.auditStatus)">
                {{ getAuditStatusText(scope.row.auditStatus) }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="统计数据" width="120">
          <template slot-scope="scope">
            <div>下载: {{ scope.row.downloadCount || 0 }}</div>
            <div>浏览: {{ scope.row.viewCount || 0 }}</div>
            <div>点赞: {{ scope.row.likeCount || 0 }}</div>
            <div>评分: {{ formatRating(scope.row.avgRating) }}</div>
          </template>
        </el-table-column>
        
        <el-table-column label="价格信息" width="100">
          <template slot-scope="scope">
            <div v-if="scope.row.isFree">
              <el-tag type="success" size="mini">免费</el-tag>
            </div>
            <div v-else-if="scope.row.requirePoints">
              <el-tag type="warning" size="mini">{{ scope.row.pointsRequired }}积分</el-tag>
            </div>
            <div v-else>
              <el-tag type="primary" size="mini">¥{{ formatAmount(scope.row.price) }}</el-tag>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="特殊标记" width="100">
          <template slot-scope="scope">
            <div>
              <el-tag v-if="scope.row.isRecommend" size="mini" type="primary">推荐</el-tag>
              <el-tag v-if="scope.row.isFeatured" size="mini" type="success">精选</el-tag>
              <el-tag v-if="scope.row.isHot" size="mini" type="danger">热门</el-tag>
            </div>
            <div v-if="scope.row.violationType" style="margin-top: 4px;">
              <el-tag size="mini" type="danger">{{ getViolationTypeText(scope.row.violationType) }}</el-tag>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="createTime" label="创建时间" width="150">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button 
              v-if="scope.row.auditStatus === 0" 
              type="primary" 
              size="mini" 
              @click="auditResource(scope.row, 1)">
              通过
            </el-button>
            
            <el-button 
              v-if="scope.row.auditStatus === 0" 
              type="warning" 
              size="mini" 
              @click="auditResource(scope.row, 2)">
              拒绝
            </el-button>
            
            <el-button 
              v-if="scope.row.resourceStatus === 2" 
              type="danger" 
              size="mini" 
              @click="takeDownResource(scope.row)">
              下架
            </el-button>
            
            <el-dropdown @command="handleCommand" trigger="click">
              <el-button type="text" size="mini">
                更多<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="{action: 'view', row: scope.row}">查看详情</el-dropdown-item>
                <el-dropdown-item :command="{action: 'download', row: scope.row}">下载资源</el-dropdown-item>
                <el-dropdown-item :command="{action: 'recommend', row: scope.row}">
                  {{ scope.row.isRecommend ? '取消推荐' : '设置推荐' }}
                </el-dropdown-item>
                <el-dropdown-item :command="{action: 'featured', row: scope.row}">
                  {{ scope.row.isFeatured ? '取消精选' : '设置精选' }}
                </el-dropdown-item>
                <el-dropdown-item :command="{action: 'hot', row: scope.row}">
                  {{ scope.row.isHot ? '取消热门' : '设置热门' }}
                </el-dropdown-item>
                <el-dropdown-item :command="{action: 'violation', row: scope.row}" divided>标记违规</el-dropdown-item>
                <el-dropdown-item :command="{action: 'delete', row: scope.row}" style="color: #F56C6C;">删除资源</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryForm.pageNum"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="queryForm.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </div>
    
    <!-- 资源详情弹窗 -->
    <el-dialog title="资源详情" :visible.sync="detailDialogVisible" width="800px">
      <div v-if="resourceDetail">
        <h3>{{ resourceDetail.title }}</h3>
        <p><strong>上传者:</strong> {{ resourceDetail.uploaderName }} ({{ getUploaderTypeText(resourceDetail.uploaderType) }})</p>
        <p><strong>资源类型:</strong> {{ getResourceTypeText(resourceDetail.resourceType) }}</p>
        <p><strong>来源:</strong> {{ getSourceText(resourceDetail.source) }}</p>
        <p><strong>学科:</strong> {{ getSubjectText(resourceDetail.subject) }}</p>
        <p><strong>文件:</strong> {{ resourceDetail.fileName }} ({{ getFileSizeText(resourceDetail.fileSize) }})</p>
        <p><strong>状态:</strong> {{ getResourceStatusText(resourceDetail.resourceStatus) }} / {{ getAuditStatusText(resourceDetail.auditStatus) }}</p>
        <p><strong>创建时间:</strong> {{ formatDateTime(resourceDetail.createTime) }}</p>
        <div style="margin-top: 20px;">
          <strong>描述:</strong>
          <div style="margin-top: 10px; padding: 10px; border: 1px solid #ddd; border-radius: 4px;">
            {{ resourceDetail.description }}
          </div>
        </div>
      </div>
    </el-dialog>
    
    <!-- 审核弹窗 -->
    <el-dialog title="审核资源" :visible.sync="auditDialogVisible" width="500px">
      <el-form :model="auditForm" label-width="100px">
        <el-form-item label="审核结果">
          <el-radio-group v-model="auditForm.auditStatus">
            <el-radio :label="1">审核通过</el-radio>
            <el-radio :label="2">审核拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="审核意见">
          <el-input 
            v-model="auditForm.auditRemark" 
            type="textarea" 
            :rows="4"
            placeholder="请输入审核意见">
          </el-input>
        </el-form-item>
      </el-form>
      
      <div slot="footer">
        <el-button @click="auditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAudit" :loading="auditLoading">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { 
  getResourceList, 
  getResourceDetail, 
  auditResource,
  batchAuditResources,
  takeDownResource,
  setResourceRecommend,
  setResourceFeatured,
  setResourceHot,
  deleteResource,
  downloadResource,
  getCommunityStatistics 
} from '@/api/community'

export default {
  name: 'ResourceManagement',
  data() {
    return {
      loading: false,
      resourceList: [],
      total: 0,
      selectedResources: [],
      statistics: {},
      
      queryForm: {
        keyword: '',
        uploaderName: '',
        resourceType: '',
        source: '',
        subject: '',
        resourceStatus: null,
        pageNum: 1,
        pageSize: 20
      },
      
      detailDialogVisible: false,
      resourceDetail: null,
      
      auditDialogVisible: false,
      auditLoading: false,
      auditForm: {
        id: null,
        auditStatus: 1,
        auditRemark: ''
      }
    }
  },
  
  created() {
    this.loadResourceList()
    this.loadStatistics()
  },
  
  methods: {
    async loadResourceList() {
      this.loading = true
      try {
        const response = await getResourceList(this.queryForm)
        if (response.code === 200) {
          this.resourceList = response.data.list
          this.total = response.data.total
        }
      } catch (error) {
        this.$message.error('加载资源列表失败')
      } finally {
        this.loading = false
      }
    },
    
    async loadStatistics() {
      try {
        const response = await getCommunityStatistics()
        if (response.code === 200) {
          this.statistics = response.data
        }
      } catch (error) {
        console.error('加载统计数据失败', error)
      }
    },
    
    handleSearch() {
      this.queryForm.pageNum = 1
      this.loadResourceList()
    },
    
    handleReset() {
      this.queryForm = {
        keyword: '',
        uploaderName: '',
        resourceType: '',
        source: '',
        subject: '',
        resourceStatus: null,
        pageNum: 1,
        pageSize: 20
      }
      this.loadResourceList()
    },
    
    handleRefresh() {
      this.loadResourceList()
      this.loadStatistics()
    },
    
    handleSizeChange(val) {
      this.queryForm.pageSize = val
      this.queryForm.pageNum = 1
      this.loadResourceList()
    },
    
    handleCurrentChange(val) {
      this.queryForm.pageNum = val
      this.loadResourceList()
    },
    
    handleSelectionChange(selection) {
      this.selectedResources = selection
    },
    
    async viewResourceDetail(row) {
      try {
        const response = await getResourceDetail(row.id)
        if (response.code === 200) {
          this.resourceDetail = response.data
          this.detailDialogVisible = true
        }
      } catch (error) {
        this.$message.error('获取资源详情失败')
      }
    },
    
    auditResource(row, status) {
      this.auditForm = {
        id: row.id,
        auditStatus: status,
        auditRemark: ''
      }
      this.auditDialogVisible = true
    },
    
    async submitAudit() {
      this.auditLoading = true
      try {
        const response = await auditResource(
          this.auditForm.id,
          this.auditForm.auditStatus,
          this.auditForm.auditRemark
        )
        
        if (response.code === 200) {
          this.$message.success('审核成功')
          this.auditDialogVisible = false
          this.loadResourceList()
        }
      } catch (error) {
        this.$message.error('审核失败')
      } finally {
        this.auditLoading = false
      }
    },
    
    async batchAudit(status) {
      if (this.selectedResources.length === 0) {
        this.$message.warning('请选择要审核的资源')
        return
      }
      
      const statusText = status === 1 ? '通过' : '拒绝'
      
      try {
        await this.$confirm(`确认批量${statusText}选中的资源？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const resourceIds = this.selectedResources.map(resource => resource.id)
        const response = await batchAuditResources(resourceIds, status, `批量${statusText}`)
        
        if (response.code === 200) {
          this.$message.success(`批量${statusText}成功`)
          this.loadResourceList()
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error(`批量${statusText}失败`)
        }
      }
    },
    
    async batchPublish() {
      this.$message.info('批量发布功能开发中')
    },
    
    async batchTakeDown() {
      this.$message.info('批量下架功能开发中')
    },
    
    async takeDownResource(row) {
      try {
        const { value } = await this.$prompt('请输入下架原因', '下架资源', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValidator: value => value && value.trim().length > 0,
          inputErrorMessage: '请输入下架原因'
        })
        
        const response = await takeDownResource(row.id, value)
        if (response.code === 200) {
          this.$message.success('下架成功')
          this.loadResourceList()
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('下架失败')
        }
      }
    },
    
    handleCommand(command) {
      const { action, row } = command
      
      switch (action) {
        case 'view':
          this.viewResourceDetail(row)
          break
        case 'download':
          this.downloadResource(row)
          break
        case 'recommend':
          this.toggleRecommend(row)
          break
        case 'featured':
          this.toggleFeatured(row)
          break
        case 'hot':
          this.toggleHot(row)
          break
        case 'violation':
          this.markViolation(row)
          break
        case 'delete':
          this.deleteResource(row)
          break
      }
    },
    
    async downloadResource(row) {
      try {
        const response = await downloadResource(row.id, 1) // 假设当前用户ID为1
        if (response.code === 200) {
          this.$message.success('下载链接：' + response.data)
        }
      } catch (error) {
        this.$message.error('下载失败')
      }
    },
    
    async toggleRecommend(row) {
      try {
        const response = await setResourceRecommend(row.id, !row.isRecommend)
        if (response.code === 200) {
          this.$message.success(row.isRecommend ? '取消推荐成功' : '设置推荐成功')
          this.loadResourceList()
        }
      } catch (error) {
        this.$message.error('操作失败')
      }
    },
    
    async toggleFeatured(row) {
      try {
        const response = await setResourceFeatured(row.id, !row.isFeatured)
        if (response.code === 200) {
          this.$message.success(row.isFeatured ? '取消精选成功' : '设置精选成功')
          this.loadResourceList()
        }
      } catch (error) {
        this.$message.error('操作失败')
      }
    },
    
    async toggleHot(row) {
      try {
        const response = await setResourceHot(row.id, !row.isHot)
        if (response.code === 200) {
          this.$message.success(row.isHot ? '取消热门成功' : '设置热门成功')
          this.loadResourceList()
        }
      } catch (error) {
        this.$message.error('操作失败')
      }
    },
    
    async markViolation(row) {
      this.$message.info('标记违规功能开发中')
    },
    
    async deleteResource(row) {
      try {
        await this.$confirm('确认删除该资源？删除后无法恢复！', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
        
        const response = await deleteResource(row.id)
        if (response.code === 200) {
          this.$message.success('删除成功')
          this.loadResourceList()
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败')
        }
      }
    },
    
    // 辅助方法
    formatDateTime(dateTime) {
      return dateTime ? new Date(dateTime).toLocaleString() : '-'
    },
    
    formatAmount(amount) {
      return amount ? Number(amount).toFixed(2) : '0.00'
    },
    
    formatRating(rating) {
      return rating ? Number(rating).toFixed(1) : '0.0'
    },
    
    getFileSizeText(size) {
      if (!size || size === 0) return '0 B'
      
      const units = ['B', 'KB', 'MB', 'GB', 'TB']
      let unitIndex = 0
      let fileSize = Number(size)
      
      while (fileSize >= 1024 && unitIndex < units.length - 1) {
        fileSize /= 1024
        unitIndex++
      }
      
      return fileSize.toFixed(2) + ' ' + units[unitIndex]
    },
    
    getResourceStatusText(status) {
      const texts = { 0: '草稿', 1: '待审核', 2: '已发布', 3: '已下架', 4: '已删除' }
      return texts[status] || '未知状态'
    },
    
    getResourceStatusType(status) {
      const types = { 0: 'info', 1: 'warning', 2: 'success', 3: 'danger', 4: 'info' }
      return types[status] || ''
    },
    
    getAuditStatusText(status) {
      const texts = { 0: '待审核', 1: '审核通过', 2: '审核拒绝' }
      return texts[status] || '待审核'
    },
    
    getAuditStatusType(status) {
      const types = { 0: 'warning', 1: 'success', 2: 'danger' }
      return types[status] || ''
    },
    
    getResourceTypeText(type) {
      const texts = { 
        'document': '文档', 'video': '视频', 'audio': '音频', 
        'image': '图片', 'course': '课程', 'other': '其他' 
      }
      return texts[type] || '文档'
    },
    
    getSourceText(source) {
      const texts = { 'community': '社区', 'teacher': '教师' }
      return texts[source] || '社区'
    },
    
    getSubjectText(subject) {
      const texts = { 
        'math': '数学', 'physics': '物理', 'chemistry': '化学', 
        'biology': '生物', 'other': '其他' 
      }
      return texts[subject] || '数学'
    },
    
    getUploaderTypeText(type) {
      const texts = { 'student': '学生', 'teacher': '教师', 'admin': '管理员' }
      return texts[type] || '学生'
    },
    
    getUploaderTypeColor(type) {
      const colors = { 'student': '', 'teacher': 'success', 'admin': 'warning' }
      return colors[type] || ''
    },
    
    getViolationTypeText(type) {
      const texts = { 
        'copyright': '版权问题', 
        'inappropriate': '不当内容', 
        'virus': '病毒文件', 
        'other': '其他' 
      }
      return texts[type] || ''
    }
  }
}
</script>

<style lang="scss" scoped>
.stat-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  
  .stat-icon {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 16px;
    
    i {
      font-size: 24px;
      color: white;
    }
  }
  
  .stat-content {
    flex: 1;
    
    .stat-title {
      font-size: 14px;
      color: #909399;
      margin-bottom: 8px;
    }
    
    .stat-value {
      font-size: 24px;
      font-weight: bold;
      color: #303133;
    }
  }
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  
  .toolbar-left {
    display: flex;
    gap: 8px;
  }
}
</style>